package sipus.common;

import java.io.IOException;
import java.util.Date;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.zkoss.spring.security.ui.ZkDisableSessionInvalidateFilter;
import org.zkoss.zkplus.hibernate.HibernateUtil;

import sipus.database.model.LogLogin;
import sipus.database.model.Tbmuser;


public class SecurityFilter extends ZkDisableSessionInvalidateFilter {

	public SecurityFilter() {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		// TODO Auto-generated method stub
		super.doFilter(arg0, arg1, arg2);

		if (arg0.getParameter("j_username") != null
				&& arg0.getParameter("j_password") != null
				&& !arg0.getParameter("j_username").trim().equals("")
				&& !arg0.getParameter("j_password").trim().equals("")) {

			String username = arg0.getParameter("j_username").trim();
			String password = Common.desEncrypter.encrypt(arg0.getParameter(
					"j_password").trim());
			Session session = HibernateUtil.getSessionFactory().openSession();

			Tbmuser users = (Tbmuser) session.createCriteria(Tbmuser.class)
					.add(Restrictions.eq("userId", username)).setMaxResults(1)
					.uniqueResult();

			LogLogin login = new LogLogin();

			login.setIp(arg0.getRemoteAddr());
			login.setKeterangan("");
			login.setLogin(new Date());
			login.setLogout(null);
			login.setNama(username);
			login.setTbmuser(users);

			login.setHostname(arg0.getServerName());
			login.setSuccess_status(users != null
					&& users.getUserPassword().equals(password));
			login.setDescription(!login.getSuccess_status() ? "Pengguna ini mencoba mengakses sistem menggunakan password "
					+ arg0.getParameter("j_password").trim()
					+ ", namun gagal login"
					: "Pengguna berhasil login");

			Transaction transaction = session.beginTransaction();
			session.save(login);
			transaction.commit();
			session.disconnect();
			session.disconnect();
			session.close();

		}

	}

}